#include "MiiFilter.h"
#include "miiPin.h"
#include "audPinIn.h"
CMiiFilter::CMiiFilter(LPUNKNOWN pUnk, HRESULT *phr,int width,int hight) : CBaseFilter(NAME("CMiiShow"), pUnk, this, GUID_NULL)
{
	m_pin = new CMiiShowPinIn(this, phr,width,hight);
	m_audpin = new CMiiAudPinIn(this, phr);
	m_pin->AddRef();
	m_audpin->AddRef();
}

CMiiFilter::~CMiiFilter(void)
{
	m_pin->Release();
	m_audpin->Release();
	//delete m_pin;
	/*delete m_audpin;*/
}

int CMiiFilter::GetPinCount(void)
{
	return 2;
	/*return 1;*/
}

CBasePin *CMiiFilter::GetPin(int n)
{
	if(n==0)
		return m_pin;
	return m_audpin;
}

template<class T> inline static T ourmax( const T & a, const T & b )
{
	return a > b ? a : b;
}
STDMETHODIMP_(ULONG) CMiiFilter::NonDelegatingAddRef()
{
	LONG lRef = InterlockedIncrement( &m_cRef );
	/*ASSERT(lRef > 0);*/
	/*DbgLog((LOG_MEMORY,3,TEXT("    Obj %d ref++ = %d"),
		m_dwCookie, m_cRef));*/
	return ourmax(ULONG(m_cRef), 1ul);
}

STDMETHODIMP_(ULONG) CMiiFilter::NonDelegatingRelease()
{
	/* If the reference count drops to zero delete ourselves */

	LONG lRef = InterlockedDecrement( &m_cRef );
	ASSERT(lRef >= 0);

	/*DbgLog((LOG_MEMORY,3,TEXT("    Object %d ref-- = %d"),
		m_dwCookie, m_cRef));*/
	if (lRef == 0) {

		// COM rules say we must protect against re-entrancy.
		// If we are an aggregator and we hold our own interfaces
		// on the aggregatee, the QI for these interfaces will
		// addref ourselves. So after doing the QI we must release
		// a ref count on ourselves. Then, before releasing the
		// private interface, we must addref ourselves. When we do
		// this from the destructor here it will result in the ref
		// count going to 1 and then back to 0 causing us to
		// re-enter the destructor. Hence we add an extra refcount here
		// once we know we will delete the object.
		// for an example aggregator see filgraph\distrib.cpp.

		m_cRef++;

		delete this;
		return ULONG(0);
	} else {
		return ourmax(ULONG(m_cRef), 1ul);
	}
}
